from pymongo import MongoClient
import datetime
import pprint

# 连接到MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client.medical_system

# 获取admin角色
admin_role = db.roles.find_one({'name': 'admin'})

if admin_role:
    print("找到admin角色:")
    print(f"ID: {admin_role['_id']}")
    print(f"名称: {admin_role.get('displayName', 'admin')}")
    
    # 获取现有权限
    current_permissions = admin_role.get('permissions', [])
    print(f"\n当前拥有 {len(current_permissions)} 个权限")
    
    # 添加医嘱管理相关的权限
    medical_order_permissions = [
        'medical_order:read',
        'medical_order:create',
        'medical_order:update',
        'medical_order:delete',
        'medical_order:execute'
    ]
    
    # 检查是否已存在这些权限
    missing_permissions = []
    for perm in medical_order_permissions:
        if perm not in current_permissions:
            missing_permissions.append(perm)
            print(f"缺少权限: {perm}")
    
    if missing_permissions:
        # 强制更新权限列表
        new_permissions = current_permissions + missing_permissions
        
        print(f"\n将添加 {len(missing_permissions)} 个权限...")
        print(f"更新后权限总数: {len(new_permissions)}")
        
        try:
            # 直接更新数据库
            result = db.roles.update_one(
                {'_id': admin_role['_id']},
                {'$set': {
                    'permissions': new_permissions,
                    'updatedAt': datetime.datetime.utcnow()
                }}
            )
            
            if result.modified_count > 0:
                print("成功更新权限!")
                
                # 验证更新
                updated_role = db.roles.find_one({'_id': admin_role['_id']})
                updated_permissions = updated_role.get('permissions', [])
                
                print(f"验证: 现在有 {len(updated_permissions)} 个权限")
                
                # 检查是否包含所有医嘱权限
                all_included = True
                for perm in medical_order_permissions:
                    if perm not in updated_permissions:
                        all_included = False
                        print(f"错误: 权限 {perm} 仍然缺失!")
                
                if all_included:
                    print("所有医嘱管理权限已成功添加!")
                    
                    # 打印所有权限
                    print("\n当前所有权限列表:")
                    for i, perm in enumerate(updated_permissions, 1):
                        print(f"{i}. {perm}")
            else:
                print("更新操作未修改任何文档，可能权限已存在")
        except Exception as e:
            print(f"更新失败: {e}")
    else:
        print("无需添加权限，所有医嘱管理权限已存在")
        
        # 打印所有权限
        print("\n当前所有权限列表:")
        for i, perm in enumerate(current_permissions, 1):
            print(f"{i}. {perm}")
else:
    print("未找到admin角色")

# 关闭连接
client.close()

print("\n提示: 请确保重新登录系统，以使新权限生效!") 